package org.springblade.common.config;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.utils.IPUtils;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.api.R;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static org.springblade.common.cache.DictCache.getKey;
import static org.springblade.core.secure.utils.AuthUtil.getClientId;

@Slf4j
@Aspect
@Component
public class NoRepeatSubmitAop {

///全局时间 2秒
    private  static final int secondtimeout = 3;

    @Autowired
    private BladeRedis bladeRedis;

    @Around("@annotation(org.springblade.common.config.NoRepeatSubmit)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        HttpServletRequest request  = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = request.getHeader("Blade-Auth");
        //获取注解
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        //目标类、方法
        String className = method.getDeclaringClass().getName();
        String name = method.getName();
        String ipKey = String.format("%s#%s",className,name);
        int hashCode = Math.abs(ipKey.hashCode());
        String key = String.format("%s_%d",token,hashCode);
        log.info("ipKey={},hashCode={},key={}",ipKey,hashCode,key);

        String value = bladeRedis.get(key);

        if (!StringUtils.isEmpty(value)){
            return R.fail("点击过快请稍等");
        }
        bladeRedis.setEx(key, IPUtils.getUUIDString(), Duration.ofSeconds(secondtimeout));
        //执行方法
        Object object = point.proceed();
        return object;
    }

}
